﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace AutoRoot
{
   public class TouchedPositionHandler
   {
      public static List<GameObject> listeners = new List<GameObject>();

      public void addListener(GameObject obj)
      {
         listeners.Add(obj);
      }

      public void rmListener(GameObject obj)
      {
         listeners.Remove(obj);
      }

      public void clearListener()
      {
         listeners.Clear();
      }

      public void handleClickEvent(Vector3 hitPoint)
      {
         foreach (GameObject obj in listeners)
         {
            if (obj.activeSelf)
            {
               if (Input.GetMouseButtonDown(0))
               {
                  obj.SendMessage("OnScreenTouchDown", hitPoint, SendMessageOptions.DontRequireReceiver);
               }
               else if (Input.GetMouseButtonUp(0))
               {
                  obj.SendMessage("OnScreenTouchUp", hitPoint, SendMessageOptions.DontRequireReceiver);
               }
               else if (Input.GetMouseButton(0))
               {
                  obj.SendMessage("OnScreenTouchStay", hitPoint, SendMessageOptions.DontRequireReceiver);
               }
            }
         }
      }

      public void handleTouchEvent(Touch touch)
      {
         Vector3 hitPoint = new Vector3(touch.position.x, touch.position.y, 0);
         foreach (GameObject obj in listeners)
         {
            if (obj.activeSelf)
            {
               if (touch.phase == TouchPhase.Began)
               {
                  obj.SendMessage("OnScreenTouchDown", hitPoint, SendMessageOptions.DontRequireReceiver);
               }
               else if (touch.phase == TouchPhase.Ended)
               {
                  obj.SendMessage("OnScreenTouchUp", hitPoint, SendMessageOptions.DontRequireReceiver);
               }
               else if (touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved)
               {
                  obj.SendMessage("OnScreenTouchStay", hitPoint, SendMessageOptions.DontRequireReceiver);
               }
               else if (touch.phase == TouchPhase.Canceled)
               {
                  obj.SendMessage("OnScreenTouchExit", hitPoint, SendMessageOptions.DontRequireReceiver);
               }
            }
         }
      }
   }
}